package com.example.zyghfeedback;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 已选择的图片显示位置
 *
 * @author summer
 */
public class CommitsActivity extends MPermissionsActivity implements View.OnClickListener {
    private TextView title;
    private Button tv_btn_logout;
    private EditText ed_idea;
    private String idea;
    private String fj;
    private ImageView iv_back;
    private GridView noScrollgridview;
    private GridAdapter adapter;
    private EditText ed_fj;
    private String ZyKey = "1d3b1b3f67b148b59cdc73e4d2635463";
    private TextView activity_selectimg_send;
    private TextView et_xz;
    //参数类型
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private SharePreferenceUtil mSharePreferenceUtil;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_commits);

        //动态判断权限
        requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0001);
        initView();
        initLogic();

        mSharePreferenceUtil = SharePreferenceUtil.getInstance(this);
        //这里做文本的重新赋值
        ed_fj.setText("" + mSharePreferenceUtil.geted_fj());
        ed_idea.setText("" + mSharePreferenceUtil.geted_idea());
    }

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case 0x0001:
                Init();
                break;
        }
    }


    public void Init() {
        //初始化控件
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        //设置gridview分割线为透明
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        //初始化适配器
        adapter = new GridAdapter(this);
        //更新数据
        adapter.update();
        //绑定图片数据
        noScrollgridview.setAdapter(adapter);
        //绑定点击事件
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //判断点击的是否是图片
                if (arg2 == Bimp.bmp.size()) {
                    //显示选择提示窗
                    //   new PopupWindows(CommitsActivity.this, noScrollgridview);
                    show();
                } else {
                    //进入图片预览页面
                    Intent intent = new Intent(CommitsActivity.this, PhotoActivity.class);
                    //传递图片标识
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });
        // activity_selectimg_send = (TextView)findViewById(R.id.activity_selectimg_send);
       /* activity_selectimg_send.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {
                List<String> list = new ArrayList<String>();
                for (int i = 0; i < Bimp.drr.size(); i++ )
                {
                    String Str = Bimp.drr.get(i).substring(Bimp.drr.get(i).lastIndexOf("/") + 1,
                            Bimp.drr.get(i).lastIndexOf("."));
                    list.add(FileUtils.SDPATH + Str + ".JPEG");
                }
                // 高清的压缩图片全部就在 list 路径里面了
                // 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
                // 完成上传服务器后 .........
                FileUtils.deleteDir();//删除保存内容
            }
        });*/
    }

    private void show() {
        final Dialog dialog = new Dialog(CommitsActivity.this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(CommitsActivity.this).inflate(R.layout.dialog_item, null);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        dialogWindow.setAttributes(lp);
        //初始化控件
        //       Button bt1 = (Button)view.findViewById(R.id.item_popupwindows_camera);
        Button bt2 = inflate.findViewById(R.id.bt_camera);
        Button bt3 = inflate.findViewById(R.id.bt_cancel);
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入预览页
                Intent intent = new Intent(CommitsActivity.this, TestPicActivity.class);
                startActivity(intent);
                dialog.dismiss();

                String stred_fj = ed_fj.getText().toString();
                String stred_idea = ed_idea.getText().toString();
                //这里做文本的保存
                mSharePreferenceUtil.seted_fj(stred_fj);
                mSharePreferenceUtil.seted_idea(stred_idea);
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器

        private int selectedPosition = -1;// 选中的位置

        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            return (Bimp.bmp.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                holder.images = (ImageView) convertView.findViewById(R.id.delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.images.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("GridAdapter.onClick position=" + position);
                    if (Bimp.drr.size() == 0) {
                        Bimp.bmp.clear();
                        Bimp.drr.clear();
                        Bimp.max = 0;
                        FileUtils.deleteDir();
                    } else if (Bimp.drr.size() > 0) {

                        String newStr = Bimp.drr.get(position).substring(Bimp.drr.get(position).lastIndexOf("/") + 1,
                                Bimp.drr.get(position).lastIndexOf("."));
                        FileUtils.delFile(newStr + ".JPEG");

                        Bimp.bmp.remove(position);
                        Bimp.drr.remove(position);
                        Bimp.max--;

                        adapter.notifyDataSetChanged();
                    }


                }
            });
            holder.images.setVisibility(View.VISIBLE);
            if (position == Bimp.bmp.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.group));
                holder.images.setVisibility(View.GONE);

                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }

            } else {
                holder.image.setImageBitmap(Bimp.bmp.get(position));
            }
            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
            public ImageView images;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.drr.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            try {
                                String path = Bimp.drr.get(Bimp.max);
                                System.out.println(path);
                                Bitmap bm = Bimp.revitionImageSize(path);
                                Bimp.bmp.add(bm);
                                String newStr = path.substring(path.lastIndexOf("/") + 1,
                                        path.lastIndexOf("."));
                                FileUtils.saveBitmap(bm, "" + newStr);
                                Bimp.max += 1;
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            } catch (IOException e) {

                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }


    protected void onRestart() {
        adapter.update();
        super.onRestart();
    }


    /*public class PopupWindows extends PopupWindow
    {

        public PopupWindows(Context mContext, View parent)
        {

              *//* View view = View.inflate(mContext, R.layout.item_popupwid, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout)view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));
            setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            setHeight(ViewGroup.LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();*//*
            final Dialog dialog = new Dialog(CommitsActivity.this,R.style.ActionSheetDialogStyle);
            View inflate = LayoutInflater.from(CommitsActivity.this).inflate(R.layout.dialog_item, null);
            dialog.setContentView(inflate);
            //初始化控件
     //       Button bt1 = (Button)view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = inflate.findViewById(R.id.bt_camera);
            Button bt3 = inflate.findViewById(R.id.bt_cancel);
            //绑定点击事件
          *//*  bt1.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    photo();
                    //关闭弹窗
                    dismiss();
                }
            });*//*
            bt2.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    //进入预览页
                    Intent intent = new Intent(CommitsActivity.this, TestPicActivity.class);
                    startActivity(intent);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    dismiss();
                }
            });

        }
    }*/

    private static final int TAKE_PICTURE = 0x000000;
    private String path = "";

   /* public void photo()
    {
        //开启相机
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //创建文件
        File file = new File(Environment.getExternalStorageDirectory() + "/myimage/",
                String.valueOf(System.currentTimeMillis()) + ".jpg");
        path = file.getPath();
        Uri imageUri = Uri.fromFile(file);
        //传递参数
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //开始跳转确定回调标识
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }*/


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.drr.size() < 9 && resultCode == -1) {
                    Bimp.drr.add(path);
                }
                break;
        }
    }


    /***
     * 初始化
     */
    private void initView() {
        title = findViewById(R.id.title);
        tv_btn_logout = findViewById(R.id.tv_btn_logout);
        ed_idea = findViewById(R.id.ed_idea);
        iv_back = findViewById(R.id.iv_back);
        ed_fj = findViewById(R.id.ed_fj);
        et_xz = findViewById(R.id.et_xz);
    }


    /**
     * 监听事件
     */
    private void initLogic() {
        tv_btn_logout.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        ed_idea.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_btn_logout) {//提交
            idea = ed_idea.getText().toString();
            fj = ed_fj.getText().toString();
            if (TextUtils.isEmpty(idea) || idea.length() < 10) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("反馈内容10-300字之间");
                builder.setNegativeButton(("OK"), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            } else {
                //这里把图片上传给后台，后台返回图片地址（建议上传图片给后台之前，图片做压缩处理）
                if (Bimp.drr != null && Bimp.drr.size() > 0) {
                    for (String s : Bimp.drr) {
                        System.out.println("CommitsActivity.onClick s=" + s);
                    }
                    uploading(Bimp.drr);
                } else {
                    getData();
                }

            }


        } else if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.ed_idea) {
            ed_idea.addTextChangedListener(new TextWatcher() {
                CharSequence temp;

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    temp = s;
                }

                @Override
                public void afterTextChanged(Editable s) {
                    et_xz.setText(("(" + "" + temp.length() + "/" + "300)"));
                }
            });
        } else if (v.getId() == R.id.noScrollgridview) {
         /*   photopickerintent intent = new photopickerintent(mainactivity.this);
            intent.setselectmodel(selectmodel.multi); //
            intent.setshowcarema(true); // 是否显示拍照
            intent.setmaxtotal(6); // 最多选择照片数量，默认为6
            intent.setselectedpaths(imagepaths); // 已选中的照片地址， 用于回显选中状态
            startactivityforresult(intent, request_camera_code);*/
        }
    }


    //当按钮点击时,执行使用OKhttp上传图片到服务器(http://blog.csdn.net/tangxl2008008/article/details/51777355)
    //注意:有时候上传图片失败,是服务器规定还要上传一个Key,如果开发中关于网络这一块出现问题,就多和面试官沟通沟通
    public void uploading(List<String> filePaths) {
        //图片上传接口地址
        String url = "http://172.28.60.97:8200/ZYGameServer_v2/v1/upload/feedback";
        //创建上传文件对象
        // File file = new File(Environment.getExternalStorageDirectory(), "big.jpg");

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        File[] mFiles = new File[filePaths.size()];
        for (int i = 0; i < filePaths.size(); i++) {
            mFiles[i] = new File(filePaths.get(i));
            //创建RequestBody封装参数
            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), mFiles[i]);
            //builder.addFormDataPart("image", "big.jpg", fileBody);
            builder.addFormDataPart("zyFile", "big.jpg", fileBody);
        }

        MultipartBody multipartBody = builder.build();

        //创建MultipartBody,给RequestBody进行设置
      /*  MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image", "big.jpg", fileBody)
                .build();*/


        //创建Request
        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .build();

        //创建okhttp对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();

        //上传完图片,得到服务器反馈数据
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.e("ff", "uploadMultiFile() e=" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                Log.i("ff", "uploadMultiFile() responseData=" + responseData);

                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    String code = jsonObject.getString("code");
                    String message = jsonObject.getString("message");
                    if ("0".equals(code)) {

                        //上传成功

                        Bimp.drr.clear();

                        strPath = jsonObject.getString("path");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //Toast.makeText(CommitsActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                getData();
                            }
                        });


                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CommitsActivity.this, message, Toast.LENGTH_SHORT).show();
                            }
                        });

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });


    }

    private String strPath = "";


    private void getData() {

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("zyno", ZyKey);
            json.put("userId", ZyagUtils.getAndroidID(CommitsActivity.this));
            json.put("model", ZyagUtils.getDeviceModle());
            json.put("osVersion", ZyagUtils.getAndroidSystemVersionName());
            json.put("language", ZyagUtils.getLanguage());
            json.put("network", ZyagUtils.GetNetype(CommitsActivity.this));
            json.put("appVersion", ZyagUtils.getPackageVersion(CommitsActivity.this));
            json.put("content", idea);
            json.put("des", fj);

            System.out.println("CommitsActivity.getData strPath=" + strPath);
            if (!TextUtils.isEmpty(strPath)) {
                json.put("imgs", strPath);//图片地址url
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
        //1 . 拿到OkHttpClient对象
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        //3 . 构建Request,将FormBody作为Post方法的参数传入
        Request request = new Request.Builder()
                .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/feedback")
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.e("ff", "getData() e=" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                Log.d("cn", "getData responseData responseData=" + responseData);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getfeedback(responseData);
                    }
                });

            }

        });


    }

    private void getfeedback(String responseData) {
        try {
            JSONObject jsonObject = new JSONObject(responseData);
            String code = jsonObject.getString("code");
            if ("0".equals(code)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(CommitsActivity.this);
                builder.setTitle("提交成功");
                builder.setNegativeButton(("OK"), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(CommitsActivity.this, FeedbackList.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                        Bimp.bmp.clear();
                        Bimp.drr.clear();
                        Bimp.max = 0;
                        FileUtils.deleteDir();



                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            //    myFeedback.add(new MyFeedbackModel(serialNumber1, createTime1, state1, message1, content1, read1, type1, source1, feedbackTime1));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void uploading2(View view) {
        //图片上传接口地址
        String url = "https://www.718shop.com/sell/sell.m.picture.upload.do";
        //创建上传文件对象
        File file = new File(Environment.getExternalStorageDirectory(), "big.jpg");

        //创建RequestBody封装参数
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //创建MultipartBody,给RequestBody进行设置
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "big.jpg", fileBody)
                .build();
        //创建Request
        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .build();

        //创建okhttp对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();

        //上传完图片,得到服务器反馈数据
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("ff", "uploadMultiFile() e=" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("ff", "uploadMultiFile() response=" + response.body().string());
            }
        });


    }

}

